package com.example.receivesms;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.webkit.WebChromeClient.CustomViewCallback;

@SuppressLint("ParserError") public class DatabaseHandler extends SQLiteOpenHelper {

	// All Static variables
	// Database Version
	private static final int DATABASE_VERSION = 1;

	// Database Name
	private static final String DATABASE_NAME = "DemoBank";

	// Contacts table name
	private static final String TABLE_ACCOUNTS = "tblAccounts";
	private static final String TABLE_TRANS = "tblTransactions";

	// Contacts Table Columns names
	private static final String KEY_ID = "AccID";
	private static final String KEY_NAME = "AccName";
	private static final String KEY_PHONE = "AccPhone";
	private static final String KEY_ACCNO = "AccNumber";
	private static final String KEY_BALAC = "AccBalance";
	
	// Transaction Column names
	private static final String TRAN_ID = "TransID";
	private static final String TRAN_SRC = "TransSource";
	private static final String TRAN_DES = "TransDestination";
	private static final String TRAN_MONEY = "TransMoney";
	private static final String TRAN_TIME = "TransTime";

	public DatabaseHandler(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	// Creating Tables
	@Override
	public void onCreate(SQLiteDatabase db) {
		String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_ACCOUNTS + "("
				+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
				+ KEY_PHONE + " TEXT," + KEY_ACCNO + " TEXT," + KEY_BALAC + " TEXT" + ")";
		db.execSQL(CREATE_CONTACTS_TABLE);
		
		String CREATE_TRANSACTION_TABLE = "CREATE TABLE " + TABLE_TRANS + "("
				+ TRAN_ID + " INTEGER PRIMARY KEY," + TRAN_SRC + " TEXT,"
				+ TRAN_DES + " TEXT," + TRAN_MONEY + " TEXT," + TRAN_TIME + " TEXT" + ")";
		db.execSQL(CREATE_TRANSACTION_TABLE);
	}

	// Upgrading database
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// Drop older table if existed
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRANS);
		// Create tables again
		onCreate(db);
	}
	
	public void deleteTable(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACCOUNTS);
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRANS);
	}
	
	

	/***************************************************************************************
	 * TRANSACTION PROCESSING FUNCTION
	 * All CRUD(Create, Read, Update, Delete) Operations
	 */

	// Adding new Transaction
	void addTransaction(Transaction trans) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(TRAN_SRC, trans.get_source()); // Contact Name
		values.put(TRAN_DES, trans.get_destination());// So dien thoai
		values.put(TRAN_MONEY, trans.get_money()); // So TK
		values.put(TRAN_TIME, trans.get_time());// So tien
		
		// Inserting Row
		db.insert(TABLE_TRANS, null, values);
		db.close(); // Closing database connection
	}

	// Getting single Transaction
	Transaction getTransaction(int id) {
		SQLiteDatabase db = this.getReadableDatabase();

		Cursor cursor = db.query(TABLE_TRANS, new String[] { TRAN_ID,
				TRAN_SRC, TRAN_DES, TRAN_MONEY, TRAN_TIME }, KEY_ID + "=?",
				new String[] { String.valueOf(id) }, null, null, null, null);
		if (cursor != null)
			cursor.moveToFirst();

		Transaction trans = new Transaction(Integer.parseInt(cursor.getString(0)),
				cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
		// return contact
		return trans;
	}
	
	// Getting All Transactions
	public List<Transaction> getAllTransactions() {
		List<Transaction> transList = new ArrayList<Transaction>();
		// Select All Query
		String selectQuery = "SELECT  * FROM " + TABLE_TRANS;

		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.rawQuery(selectQuery, null);

		// looping through all rows and adding to list
		if (cursor.moveToFirst()) {
			do {
				Transaction trans = new Transaction();
				trans.set_id(Integer.parseInt(cursor.getString(0)));
				trans.set_source(cursor.getString(1));
				trans.set_destination(cursor.getString(2));
				trans.set_money(cursor.getString(3));
				trans.set_time(cursor.getString(4));
				
				// Adding contact to list
				transList.add(trans);
			} while (cursor.moveToNext());
		}

		return transList;
	}

	// Updating single Transaction
	public int updateTransaction(Transaction transaction) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(TRAN_SRC, transaction.get_source());
		values.put(TRAN_DES, transaction.get_destination());
		values.put(TRAN_MONEY, transaction.get_money());
		values.put(TRAN_TIME, transaction.get_time());
		
		// updating row
		return db.update(TABLE_TRANS, values, KEY_ID + " = ?",
				new String[] { String.valueOf(transaction.get_id()) });
	}

	// Deleting single Transaction
	public void deleteTransaction(Transaction transaction) {
		SQLiteDatabase db = this.getWritableDatabase();
		db.delete(TABLE_TRANS, TRAN_ID + " = ?",
				new String[] { String.valueOf(transaction.get_id()) });
		db.close();
	}


	// Getting Transactions Count
	public int getTransactionsCount() {
		String countQuery = "SELECT * FROM " + TABLE_TRANS;
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(countQuery, null);
		cursor.close();

		// return count
		return cursor.getCount();
	}
	
	/***************************************************************************************
	 * CONTACT PROCESSING FUNCTION
	 */
	// Adding new contact
		void addContact(Contact contact) {
			SQLiteDatabase db = this.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put(KEY_NAME, contact.getName()); // Contact Name
			values.put(KEY_PHONE, contact.get_phone());// So dien thoai
			values.put(KEY_ACCNO, contact.getAccNumber()); // So TK
			values.put(KEY_BALAC, contact.getBalance());// So tien
			
			// Inserting Row
			db.insert(TABLE_ACCOUNTS, null, values);
			db.close(); // Closing database connection
		}

		// Getting single contact
		Contact getContact(int id) {
			SQLiteDatabase db = this.getReadableDatabase();

			Cursor cursor = db.query(TABLE_ACCOUNTS, new String[] { KEY_ID,
					KEY_NAME, KEY_PHONE, KEY_ACCNO, KEY_BALAC }, KEY_ID + "=?",
					new String[] { String.valueOf(id) }, null, null, null, null);
			if (cursor != null)
				cursor.moveToFirst();

			Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
					cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
			// return contact
			return contact;
		}
		
		// Getting single contact
		public Contact getContact(String accNo) {
			SQLiteDatabase db = this.getReadableDatabase();

			Cursor cursor = db.query(TABLE_ACCOUNTS, new String[] { KEY_ID,
					KEY_NAME, KEY_PHONE, KEY_ACCNO, KEY_BALAC }, KEY_ACCNO + "=?",
					new String[] { String.valueOf(accNo) }, null, null, null, null);
			if (cursor != null)
				cursor.moveToFirst();

			Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
					cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
			// return contact
			return contact;
		}
		
		// Getting All Contacts
		public List<Contact> getAllContacts() {
			List<Contact> contactList = new ArrayList<Contact>();
			// Select All Query
			String selectQuery = "SELECT * FROM " + TABLE_ACCOUNTS;

			SQLiteDatabase db = this.getWritableDatabase();
			Cursor cursor = db.rawQuery(selectQuery, null);

			// looping through all rows and adding to list
			if (cursor.moveToFirst()) {
				do {
					Contact contact = new Contact();
					contact.setID(Integer.parseInt(cursor.getString(0)));
					contact.setName(cursor.getString(1));
					contact.set_phone(cursor.getString(2));
					contact.setAccNumber(cursor.getString(3));
					contact.setBalance(cursor.getString(4));
					
					// Adding contact to list
					contactList.add(contact);
				} while (cursor.moveToNext());
			}

			// return contact list
			return contactList;
		}

		// Updating single contact
		public int updateContact(Contact contact) {
			SQLiteDatabase db = this.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put(KEY_NAME, contact.getName());
			values.put(KEY_PHONE, contact.get_phone());
			values.put(KEY_ACCNO, contact.getAccNumber());
			values.put(KEY_BALAC, contact.getBalance());
			
			// updating row
			return db.update(TABLE_ACCOUNTS, values, KEY_ID + " = ?",
					new String[] { String.valueOf(contact.getID()) });
		}

		// Deleting single contact
		public void deleteContact(Contact contact) {
			SQLiteDatabase db = this.getWritableDatabase();
			db.delete(TABLE_ACCOUNTS, KEY_ID + " = ?",
					new String[] { String.valueOf(contact.getID()) });
			db.close();
		}

		// Deleting single contact
		public void deleteAllContact() {
			for (int i=0;i<getContactsCount();i++) {
				deleteContact(getContact(i));
			}
		}

		// Getting contacts Count
		public int getContactsCount() {
			String countQuery = "SELECT  * FROM " + TABLE_ACCOUNTS;
			SQLiteDatabase db = this.getReadableDatabase();
			Cursor cursor = db.rawQuery(countQuery, null);
			cursor.close();

			// return count
			return cursor.getCount();
		}
	/***************************************************************************************/
}
